package com.example.demo.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class DownloadUtils {
    /**
     * 批量下载
     * zip
     * @param fileNameList
     * //@param response , HttpServletResponse response
     */
    public static void downloadFile(List<String> fileNameList,HttpServletResponse response) {
        ServletOutputStream os = null;
        ZipOutputStream zos = null;
        BufferedInputStream bis = null;
        FileInputStream in = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();

            if (null != fileNameList && fileNameList.size() > 0) {
                //通过response对象获取OutputStream流
                os = response.getOutputStream();
                //zip输出流
                zos = new ZipOutputStream(os);
                //遍历 filePath文件路径
                for (String filePath : fileNameList) {
                    //获取文件名称
                    String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
                    File file = new File(filePath);
                    if (file.exists()) {
                        //读取文件
                        in = new FileInputStream(file);
                        //创建zip 压缩包
                        ZipEntry zipEntry = new ZipEntry(fileName);
                        zos.putNextEntry(zipEntry);
                        //设置压缩包文件名
                        String zipFileName = "dataFile.zip";
                        //设置Content-Disposition响应头，控制浏览器弹出，设置中文名称编码
                        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8"));
                        //输入缓冲流
                        bis = new BufferedInputStream(in, 1024 * 10);
                        byte[] buf = new byte[1024 * 10];//读写缓冲区
                        int len = 0;
                        while ((len = bis.read(buf, 0, 1024 * 10)) > 0) {
                            //使用outputstream将缓冲区数据输出到浏览器
                            zos.write(buf, 0, len);
                        }
                        bis.close();
                        in.close();
                        zos.closeEntry();
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }


    public void batchDownload( List<String> data, HttpServletResponse response) {

        //各个文件压缩包临时存放路径集合
        List<String> zipList = new ArrayList();
        //Linux版创建临时zip,总存放压缩文件   AcasConfig.getProfile()= D:/home/acas/uploadPath/临时zip.zip
        String totalZip = "D:\\test\\临时zip.zip";
        try {
            for (String d : data) {
                //获取文件名称
                String fileName = d.substring(d.lastIndexOf("\\") + 1);
                //Linux版创建临时文件
                String zipFilePath = "D:\\test\\" + fileName + ".zip";
                zipList.add(zipFilePath);
            }
            //判断有无订单需要下载文件，没有直接相应前台"没有需要下载的文件!"，直接结束方法
//            if (CollectionUtils.isEmpty(zipList)) {
//                return AjaxResult.error("没有需要下载的文件!");
//            }
            // 设置Content-Disposition响应头，控制浏览器弹出保存框，若没有此句浏览器会直接打开并显示文件
            // 中文名要进行URLEncoder.encode编码，否则客户端能下载但名字会乱码
            String orderDocuments = "记录文件.zip";
            String filenames = URLEncoder.encode(orderDocuments, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + filenames + ";" + "filename*=utf-8''" + filenames);
            //该流不可以手动关闭,手动关闭下载会出问题,下载完成后会自动关闭
            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream inputStream = new FileInputStream(totalZip);
            // 如果是SpringBoot框架,在这个路径 需要org.apache.tomcat.util.http.fileupload.IOUtils产品否则，需要自主引入apache的 commons-io依赖
            // copy方法为文件复制,在这里直接实现了下载效果
            IOUtils.copy(inputStream, outputStream);
            inputStream.close();
            //下载完成之后，删掉临时zip包
            zipList.add(totalZip);
            for (String zipListPath : zipList) {
                File fileTempZip = new File(zipListPath);
                fileTempZip.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }




}
